﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MVVMFramework
{
    /// <summary>
    /// This class is responsible for maintaining a collection of regions and attaching regions to controls. Modules uses this class to get necessary region.
    /// </summary>
    public class RegionManager
    {
        readonly object syncRegions;
        /// <summary>
        /// Stores the regions
        /// </summary>
        private readonly Dictionary<Type, IRegion> regions;

        /// <summary>
        /// Initializes a new instance of the <see cref="RegionManager"/> class.
        /// </summary>
        internal RegionManager()
        {
            regions = new Dictionary<Type, IRegion>();
            syncRegions = new object();
        }

        public static readonly RegionManager Default = new RegionManager();

        /// <summary>
        /// Registers the region for public access.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="region">The region.</param>
        public void RegisterRegion<T>(T region) where T : class,IRegion
        {
            lock (syncRegions)
            {
                if (regions.ContainsKey(typeof(T)))
                    throw new Exception(string.Format("Region {0} already registered", typeof(T).FullName));

                regions[typeof(T)] = region;
            }
        }
        
        /// <summary>
        /// Resolves registered region.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T ResolveRegion<T>() where T : class,IRegion
        {
            lock (syncRegions)
            {
                IRegion region;
                if (!regions.TryGetValue(typeof(T), out region))
                    return null;
                return region as T;
            }
        }
    }
}
